<?php namespace framework\Model;

use Pdo;

class Db
{
	public $table;

	private $pdo;

	private $option=[

		'where'=>'',
		'groupBy'=>'',
		'orderBy'=>'',
		'having'=>'',
		'limit'=>''
	];

	//构造函数
	public function __construct($table)
	{
		$this->table = $table;

		$this->connect();
	}
	//Pdo链接数据库
	private function connect()
	{
		$dsn = 'mysql:host='.C('db_host').';dbname='.C('db_database');
		// print_r(C('db_host'));
		try {
			$this->pdo = new Pdo($dsn,C('db_user'),C('db_password'));
			$this->pdo->query('set names utf8');
		} catch (PDOException $e) {
			die($e->getMessage());
			exit;
		}
	}

	// 只做查询
	public function query($sql,$parmas=[])
	{
		// 执行预处理
		$sth = $this->pdo->prepare($sql);
		$id=0;

		foreach ($parmas as $p) {
			
			$id++;
			$var = "hd{$id}";
			$$var = $p;
			// 绑定参数
			$sth->bindParam($id,$$var,PDO::PARAM_STR);
		}
		// 执行  查询函数
		$sth->execute();
		// 从结果集中获取以列名为索引的关联数组。
		return $sth->fetchAll(PDO::FETCH_ASSOC);

	}

	//执行  增删改
	public function execute($sql,$parmas=[])
	{	
		//预处理
		$sth = $this->pdo->prepare($sql);
		$id=0;
		foreach ($parmas as $p) {
			
			$id++;
			$var = "hd{$id}";
			$$var = $p;
			//绑定参数
			$sth = bindParam($id,$$var,PDO::PAREM_STR);
		}
		// 返回执行
		return $sth->execute();

	}

	// 查询方式
	public function select()
	{
		$sql = ' SELECT * FROM '.$this->table." {$this->option['where']}
		 {$this->option['groupBy']} {$this->option['having']} {$this->option['orderBy']}
		  {$this->option['limit']}"; 
		  // print_r($sql);
		  return $this->query($sql);
	}


	// where 
	public function where($arg)
	{
		$this->option['where']=" WHERE $arg";
		return $this;
	}

	// groupBy
	public function groupBy($arg)
	{
		$this->option['groupBy']=" GROUP BY $arg";
		return $this;
	}

	//orderBy
	public function orderBy($arg)
	{
		$this->option['orderBy']=" ORDER BY $arg";
		return $this;
	}

	//limit
	public function limit($arg)
	{
		$this->option['limit']=" LIMIT $arg";
		return $this;
	}

	// having
	public function having($arg)
	{
		$this->option['having']=" HAVING $arg";
		return $this;
	}

}








 ?>